package com.mapaoer.user.security;


import com.mapaoer.user.service.impl.UserDetailsServiceImpl;
import com.mapaower.user.utils.JwtTokenProvider;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器
 * 简化版实现，移除了Spring Security依赖
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Autowired
    private JwtTokenProvider tokenProvider;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        try {
            // 获取请求中的JWT Token
            String jwt = getJwtFromRequest(request);

            // 验证Token（简化版，只检查格式）
            if (StringUtils.hasText(jwt)) {
                // 从Token中获取用户名（简化版，实际应从JWT中解析）
                // 这里假设Token格式为：Bearer username
                String username = jwt.replace("Bearer ", "");
                
                // 检查用户是否有效
                if (userDetailsService.isValidUser(username)) {
                    // 简化版实现，不设置安全上下文
                    // 实际应用中应使用Spring Security的认证机制
                    logger.info("用户认证通过: {}", username);
                }
            }
        } catch (Exception ex) {
            logger.error("用户认证失败: {}", ex.getMessage());
        }

        // 继续过滤器链
        filterChain.doFilter(request, response);
    }

    /**
     * 从请求头中获取JWT Token
     */
    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}